package logic

import (
	"8-dshop/models"
	"context"
	"errors"
	"gorm.io/gorm"

	"8-dshop/shoprpc/internal/svc"
	"8-dshop/shoprpc/shoprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductAddLogic {
	return &ProductAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProductAddLogic) ProductAdd(in *shoprpc.ProductAddRequest) (*shoprpc.ProductAddResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User

	if err := user.FindUserById(models.DB, in.UserId); err != nil {
		return nil, err
	}
	if user.ID == 0 {
		return nil, errors.New("用户不存在")
	}
	product := models.Product{
		Model:  gorm.Model{},
		Title:  in.Title,
		Price:  float64(in.Price),
		Stock:  in.Stock,
		UserId: in.UserId,
		Image:  in.Image,
		Info:   in.Info,
	}

	if err := product.CreatedProduct(models.DB); err != nil {
		return nil, err
	}
	return &shoprpc.ProductAddResponse{
		ProductId: int64(product.ID),
	}, nil
}
